/**
 * 薪资管理模块
 * 负责管理员工薪资信息，包括基本工资、奖金、扣除项和总工资等
 */

// 定义状态
const state = {
  // 薪资列表，包含初始数据
  list: [
    { id: 1, employeeId: 1, employeeName: '张三', department: '技术部', position: '前端开发工程师', baseSalary: 15000, bonus: 3000, deduction: 1000, total: 15000, month: '2025-05' },
    { id: 2, employeeId: 2, employeeName: '李四', department: '人事部', position: '人事专员', baseSalary: 8000, bonus: 1000, deduction: 500, total: 8500, month: '2025-05' },
    { id: 3, employeeId: 3, employeeName: '王五', department: '财务部', position: '财务经理', baseSalary: 25000, bonus: 1000, deduction: 500, total: 25000, month: '2025-05' },
    { id: 4, employeeId: 4, employeeName: '赵六', department: '市场部', position: '市场专员', baseSalary: 8500, bonus: 1000, deduction: 500, total: 8500, month: '2025-05' }
  ]
}

// 定义mutation
const mutations = {
  // 设置薪资列表
  SET_LIST(state, list) { state.list = list },
  // 添加新薪资记录
  ADD_SALARY(state, item) { state.list.push(item) },
  // 编辑薪资记录
  EDIT_SALARY(state, item) {
    const idx = state.list.findIndex(s => s.id === item.id)
    if (idx !== -1) state.list.splice(idx, 1, item)
  },
  // 删除薪资记录
  DELETE_SALARY(state, id) {
    state.list = state.list.filter(s => s.id !== id)
  }
}

// 定义action
const actions = {
  // 获取薪资列表
  fetchList({ commit, state }) {
    // 如果已有数据，直接使用
    if (state.list && state.list.length > 0) {
      console.log('salary.js: state already populated, skipping initial fetch');
      return;
    }
    commit('SET_LIST', state.list)
  },

  // 添加新薪资记录
  addSalary({ commit, state }, item) {
    // 生成新薪资记录ID
    item.id = state.list.length ? Math.max(...state.list.map(s => s.id)) + 1 : 1
    commit('ADD_SALARY', item)
  },

  // 编辑薪资记录
  editSalary({ commit }, item) {
    commit('EDIT_SALARY', item)
  },

  // 删除薪资记录
  deleteSalary({ commit }, id) {
    commit('DELETE_SALARY', id)
  }
}

// 导出模块
export default {
  namespaced: true, // 启用命名空间
  state,
  mutations,
  actions
} 